const App = getApp()
import { CouponModel } from '../../../../models/coupon.js'
const ModelCoupon = new CouponModel()

Page({
  data:{
    couponCardNo:'',
    couponCardPassword:'',
    iphoneX: App.globalData.isIphoneX,
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar:false
  },
  onLoad:function(options){
    const self = this;
    if(options.couponCardNo){
      self.setData({
        couponCardNo:options.couponCardNo
      })
    }
    
  },

  //输入卡号
  inputCardNo:function(e){
      this.setData({
        couponCardNo:e.detail.value
      })
  },

  //输入激活码
  inputCardPassword:function(e){
    this.setData({
      couponCardPassword:e.detail.value
    })
  },

  //扫码
  scan:function(){
    const self = this;
    wx.scanCode({
      success(res) {
        self.setData({
          couponCardNo:res.result
        })
      },
      fail(){
        // App.WxService.showToast({ title: '扫码失败', icon: 'none' });
      },
      complete(){
        
      }
    })
  },


  //激活
  submit:function(){
    if(!this.data.couponCardNo){
      App.WxService.showToast({ title: '请输入卡号', icon: 'none' });
      return;
    }
    if(this.data.couponCardNo.length != 18){
      App.WxService.showToast({ title: '请输入18位卡号', icon: 'none' });
      return;
    }
    if(!this.data.couponCardPassword){
      App.WxService.showToast({ title: '请输入激活码', icon: 'none' });
      return;
    }
    var patrn = /^[A-Za-z0-9]+$/;
    if(!patrn.test(this.data.couponCardPassword)){
      App.WxService.showToast({ title: '激活码只能由字母和数字组成', icon: 'none' });
      return;
    }
    if(this.data.couponCardPassword.length != 8){
      App.WxService.showToast({ title: '请输入8位激活码', icon: 'none' });
      return;
    }
    

    const params = {
      couponCode:this.data.couponCardNo,
      activateCode:this.data.couponCardPassword
    }
    ModelCoupon.addCoupon(params).then(res => {
      wx.showToast({ 
        title: '添加成功',
        icon: 'none',
        duration: 2000 ,
        success:function(res){
          wx.redirectTo({
            url:'/pages/account/coupon/index'
          })
        }
     });
    }).catch();
  }
})